// Copyright 2019 The rhyme_lph Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// n [author] rhyme_lph
// r [email]  rhymelph@gmail.com
// Z [github] https://github.com/rhymelph

import 'package:base_plugin/base_plugin.dart';
import 'package:finance_app/generated/l10n.dart';
import 'package:finance_app/src/common/app_colors.dart';
import 'package:finance_app/src/common/app_spaces.dart';
import 'package:finance_app/src/entities/product_entity.dart';
import 'package:finance_app/src/entities/services_entity.dart';
import 'package:finance_app/src/utils/cash_utils.dart';
import 'package:finance_app/src/utils/language_utils.dart';
import 'package:finance_app/src/utils/reg_exp_utils.dart';
import 'package:finance_app/src/widgets/button/normal_float_text_button.dart';
import 'package:finance_app/src/widgets/button/normal_float_text_white_button.dart';
import 'package:finance_app/src/widgets/list_item/list_header_item.dart';
import 'package:finance_app/src/widgets/common_app_bar.dart';
import 'package:finance_app/src/widgets/input/search_input_field.dart';
import 'package:finance_app/src/widgets/select/product_radio.dart';
import 'package:finance_app/src/widgets/select/service_radio.dart';
import 'package:flutter/material.dart';
import 'package:finance_app/src/provider/dashboard/products_services/batch_products_and_services_provider.dart';
import 'package:finance_app/src/router_gen/router_meta.dart';
import 'package:flutter_sticky_header/flutter_sticky_header.dart';
import 'package:tuple/tuple.dart';

@RouterMeta(paramName: "batchProductsAndServicesPage")
class BatchProductsAndServicesPage extends StatefulWidget {
  final String type; //delete ,deactivate activate;
  final bool isService; //是否为服务
  final String status; // 状态

  const BatchProductsAndServicesPage(
      {Key key, this.type, this.isService, this.status})
      : super(key: key);

  @override
  _BatchProductsAndServicesPageState createState() =>
      _BatchProductsAndServicesPageState();
}

class _BatchProductsAndServicesPageState
    extends State<BatchProductsAndServicesPage>
    with
        PagePresenter<BatchProductsAndServicesPage,
            BatchProductsAndServicesProvider> {
  @override
  PreferredSizeWidget get appBar => getDefaultAppBar(
      title:
          '${LanguageUtils.translateAction(widget.type)} ${widget.isService ? S.current.services : S.current.products}');

  @override
  void initState() {
    provider.isService = widget.isService;
    provider.type = widget.type;
    provider.currentSelectStatus = widget.status;
    print('status:${provider.currentSelectStatus}');
    super.initState();
  }

  @override
  Widget get buildWidget => Stack(
        children: [
          ColoredBox(
            color: Colors.white,
            child: Column(
              children: [
                AppSpaces.h20,
                SearchInputField(
                  controller: provider.searchController,
                  focusNode: provider.searchFocusNode,
                ),
                AppSpaces.h20,
                Expanded(
                  child: listBuilder<Tuple3<String, bool, int>>(
                    selector: (_, __) => Tuple3<String, bool, int>(
                        __.searchController.text,
                        __.isLoadFinish,
                        widget.isService
                            ? __.allServiceData.length
                            : __.allProductData.length),
                    builder: (BuildContext context,
                            Tuple3<String, bool, int> value, Widget child) =>
                        value.item2 == false
                            ? buildLoadingWidget
                            : buildSearchWidget(value.item1).length == 0
                                ? super.buildEmptyWidget
                                : CustomScrollView(
                                    slivers: buildSearchWidget(value.item1),
                                  ),
                  ),
                ),
              ],
            ),
          ),
          _buildBottomBar(),
        ],
      );

  Widget _buildBottomBar() => Positioned(
      bottom: getDp(32) + MediaQuery.of(context).padding.bottom,
      left: 0.0,
      right: 0.0,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          NormalFloatTextWhiteButton(
            title: S.current.cancel,
            onTap: provider.onCancel,
          ),
          SizedBox(
            width: getDp(15),
          ),
          NormalFloatTextButton(
            title: typeString,
            onTap: () => provider.onOperation(widget.isService, widget.type),
          ),
        ],
      ));

  String get typeString => LanguageUtils.translateAction(widget.type);

  List<Widget> buildSearchWidget(String value) {
    List<Widget> slivers;
    // if (provider.searchController.text.isNotEmpty) {
    slivers = provider.searchData.entries
        .toList()
        .where(widget.isService
            ? _onSearchServiceInputGroup
            : _onSearchProductInputGroup)
        .map((e) => widget.isService
            ? buildServiceSliver(
                e.key,
                _onSearchServiceInputItem(
                    (e.value as List).cast<ServicesEntity>()))
            : buildProductSliver(
                e.key,
                _onSearchProductInputItem(
                    (e.value as List).cast<ProductEntity>())))
        .toList();
    // } else {
    //   slivers = provider.searchData.entries
    //       .toList()
    //       .map((e) => widget.isService
    //           ? buildServiceSliver(
    //               e.key,
    //               _onSearchServiceInputItem(
    //                   (e.value as List).cast<ServicesEntity>()))
    //           : buildProductSliver(
    //               e.key,
    //               _onSearchProductInputItem(
    //                   (e.value as List).cast<ProductEntity>())))
    //       .toList();
    // }
    return slivers;
  }

  Widget buildProductSliver(String title, List<ProductEntity> data) =>
      SliverStickyHeader(
        header: buildSliverHeader(title: title),
        sliver: SliverList(
          delegate: SliverChildBuilderDelegate(
            (context, i) => buildProductSliverItem(data, i),
            childCount: data.length,
          ),
        ),
      );

  Widget buildProductSliverItem(List<ProductEntity> data, int i) {
    ProductEntity lastItemInList = provider.searchData.entries
        .toList()
        .where(_onSearchProductInputGroup)
        .map((e) => _onSearchProductInputItem((e.value).cast<ProductEntity>()))
        .toList()
        .last
        .last;

    return listBuilder<bool>(
        selector: (_, __) => __.currentSelectProduct.contains(data[i]),
        builder: (BuildContext context, bool value, Widget child) => Column(
              children: [
                PressedOpacityButton(
                  onPressed: () => provider.onSelectProduct(data[i]),
                  padding: EdgeInsets.symmetric(
                    horizontal: getDp(29),
                    vertical: getDp(21),
                  ),
                  border: data.length == i + 1
                      ? null
                      : Border(
                          bottom: BorderSide(
                              color: aceGrayColor, width: getDp(0.5))),
                  color:
                      value == true ? aceSelectBackgroundColor : Colors.white,
                  child: ProductCheckBox(
                    isSelect: value,
                    enableInventory: data[i].enableInventory == 1,
                    title: data[i].name,
                    isSelectMode: true,
                    isActivated: data[i].isActivated == 1,
                    sellBuy:
                        '${data[i].currencyCode} ${data[i].enableSell == 0 ? '-' : CashUtils.formatCashAmount(data[i].price)} / ${data[i].enablePurchase == 0 ? '-' : CashUtils.formatCashAmount(data[i].purchasePrice)}',
                    amount: data[i].inventoryLeft ?? 0,
                    unit: data[i].unitTypeText,
                  ),
                ),
                if (lastItemInList == data[i]) AppSpaces.h85(context),
              ],
            ));
  }

  Widget buildSliverHeader({String title}) {
    final String _title = title.isEmpty ? "*" : title;
    return ListHeaderItem(
      title: _title,
    );
  }

  bool _onSearchProductInputGroup(MapEntry<String, dynamic> element) {
    return _onSearchProductInputItem(element.value).length > 0;
  }

  bool _onSearchServiceInputGroup(MapEntry<String, dynamic> element) {
    return _onSearchServiceInputItem(element.value).length > 0;
  }

  List<ProductEntity> _onSearchProductInputItem(dynamic element) {
    String searchInput = provider.searchController.text;
    List<ProductEntity> data = [];
    for (final item in element) {
      if (RegExpUtils.getSearchRegExp(searchInput).hasMatch(item.name)) {
        data.add(item);
      }
    }
    return data;
  }

  List<ServicesEntity> _onSearchServiceInputItem(dynamic element) {
    String searchInput = provider.searchController.text;
    List<ServicesEntity> data = [];
    for (final item in element) {
      if (RegExpUtils.getSearchRegExp(searchInput).hasMatch(item.name)) {
        data.add(item);
      }
    }
    return data;
  }

  Widget buildServiceSliver(String title, List<ServicesEntity> data) =>
      SliverStickyHeader(
        header: buildSliverHeader(title: title),
        sliver: SliverList(
          delegate: SliverChildBuilderDelegate(
            (context, i) => buildServiceSliverItem(data, i),
            childCount: data.length,
          ),
        ),
      );

  Widget buildServiceSliverItem(List<ServicesEntity> data, int i) {
    ServicesEntity lastItemInList = provider.searchData.entries
        .toList()
        .where(_onSearchServiceInputGroup)
        .map((e) => _onSearchServiceInputItem((e.value).cast<ServicesEntity>()))
        .toList()
        .last
        .last;
    return listBuilder<bool>(
        selector: (_, __) => widget.isService
            ? __.currentSelectService.contains(data[i])
            : __.currentSelectProduct.contains(data[i]),
        builder: (BuildContext context, bool value, Widget child) => Column(
              children: [
                PressedOpacityButton(
                  onPressed: () => provider.onSelectService(data[i]),
                  padding: EdgeInsets.symmetric(
                    horizontal: getDp(29),
                    vertical: getDp(21),
                  ),
                  border: Border(
                      bottom:
                          BorderSide(color: aceGrayColor, width: getDp(0.5))),
                  color:
                      value == true ? aceSelectBackgroundColor : Colors.white,
                  child: ServiceCheckBox(
                    isSelect: value,
                    isSelectMode: true,
                    title: data[i].name,
                    isActivated: data[i].isActivated == 1,
                    sellBuy:
                        '${data[i].currencyCode} ${data[i].enableSell == 0 ? '-' : CashUtils.formatCashAmount(data[i].price)} / ${data[i].enablePurchase == 0 ? '-' : CashUtils.formatCashAmount(data[i].purchasePrice)}',
                  ),
                ),
                if (lastItemInList == data[i]) AppSpaces.h85(context),
              ],
            ));
  }
}
